#!/usr/bin/env python

import os, sys, time, re, getopt, getpass
import traceback
import pexpect

cmdPrompt	 = '[#$] ' 
termPrompt = '(?i)terminal type\?'
termType = 'vt100'
sshKey = '(?i)do you wish to continue connecting'

def quit():
    print globals()['__doc__']
    os._exit(1)

def main():

    global cmdPrompt, termPrompt, termType, sshKey
    ########################################
    ## Parse the options
    ########################################
    try:
        optlist, args = getopt.getopt(sys.argv[1:], 'h?s:u:p:', ['help','h','?'])
    except Exception, e:
        print str(e)
        quit()
    options = dict(optlist)
    if len(args) > 1:
        quit()

    if [elem for elem in options if elem in ['-h','--h','-?','--?','--help']]:
        print "Help:"
        quit()

    user = '?????'
    host = '?????'
    password = '????'

    
    # Login via SSH
    
    child = pexpect.spawn('ssh -l %s %s'%(user, host), timeout=None)
    i = child.expect([pexpect.TIMEOUT, sshKey, cmdPrompt, '(?i)password', pexpect.EOF])
    if i == 0: # Timeout
        print 'unable to login.'
        print child.before, child.after
        print str(child)
        #sys.exit (1)
    if i == 1: 
        child.sendline ('yes')
        child.expect ('(?i)password')
    if i == 2:
        pass
    if i == 3:
        child.sendline(password)
        i = child.expect ([cmdPrompt, termPrompt])
        if i == 1:
            child.sendline (termType)
            child.expect (cmdPrompt)

    cmdPrompt = "\[PEXPECT\]\$ "
    child.sendline ("PS1='[PEXPECT]\$ '") 
    i = child.expect ([pexpect.TIMEOUT, cmdPrompt], timeout=None)
    if i == 0:
        print "unable to set prompt."
        child.sendline ("set prompt='[PEXPECT]\$ '")
        i = child.expect ([pexpect.TIMEOUT, cmdPrompt], timeout=None)
        if i == 0:
            print "unable to set prompt."
            print "response"
            print child.before
            sys.exit (1)

    print '---------------------------------------'
    print 'Report of <command> run on remote host.'
    print '---------------------------------------'

    # Run any custom commands
    child.sendline ('"/cygdrive/c/Program Files/programName.exe"')
    child.expect (cmdPrompt)
    print child.before

    # Now exit the remote host.
    child.sendline ('exit')
    index = child.expect([pexpect.EOF, "(?i)there are stopped jobs"])
    if index==1:
        child.sendline("exit")
        child.expect(EOF)

if __name__ == "__main__":

    try:
        main()
    except Exception, e:
        print str(e)
        traceback.print_exc()
        os._exit(1)
